/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainTemplateHistory;
import org.springblade.modules.admin.entity.MaintainTemplateSceneRelation;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainTemplateHistoryService;
import org.springblade.modules.admin.service.IMaintainTemplateSceneRelationService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.MaintainTemplateSceneType;
import org.springblade.modules.admin.vo.MaintainTemplateSceneTypeVO;
import org.springblade.modules.admin.wrapper.MaintainTemplateSceneTypeWrapper;
import org.springblade.modules.admin.service.IMaintainTemplateSceneTypeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 模板场景分类 控制器
 *
 * @author lsay
 * @since 2023-12-13
 */
@RestController
@AllArgsConstructor
@RequestMapping("/maintain/template/scene/type")
@Api(value = "模板场景分类", tags = "模板场景分类接口")
public class MaintainTemplateSceneTypeController extends BladeController {

	private final IMaintainTemplateSceneTypeService maintainTemplateSceneTypeService;
	private final IMaintainTemplateSceneRelationService templateSceneRelationService;
	private final IMaintainTemplateHistoryService templateHistoryService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入maintainTemplateSceneType")
	public R<MaintainTemplateSceneTypeVO> detail(MaintainTemplateSceneType maintainTemplateSceneType) {
		MaintainTemplateSceneType detail = maintainTemplateSceneTypeService.getOne(Condition.getQueryWrapper(maintainTemplateSceneType));
		return R.data(MaintainTemplateSceneTypeWrapper.build().entityVO(detail));
	}

	/**
	 * 查询全部 模板场景分类
	 */
	@GetMapping("/list/all")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查询全部", notes = "传入maintainTemplateSceneType")
	public R<List<MaintainTemplateSceneTypeVO>> listAll(MaintainTemplateSceneType maintainTemplateSceneType) {
		List<MaintainTemplateSceneType> list;
		if(Func.isNotEmpty(maintainTemplateSceneType) && Func.isNotEmpty(maintainTemplateSceneType.getMaintainType())){
			list = maintainTemplateSceneTypeService.list(Wrappers.<MaintainTemplateSceneType>lambdaQuery().eq(MaintainTemplateSceneType::getMaintainType,maintainTemplateSceneType.getMaintainType()).orderByAsc(MaintainTemplateSceneType::getSort));
		}else {
			list = maintainTemplateSceneTypeService.list(Wrappers.<MaintainTemplateSceneType>lambdaQuery().orderByAsc(MaintainTemplateSceneType::getSort));
		}
		List<MaintainTemplateSceneTypeVO> result = new ArrayList<>();
		if(Func.isNotEmpty(list)){
			list.forEach(e -> {
				MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
				vo.setId(e.getId());
				vo.setName(e.getName());
				vo.setDesc(e.getDesc());
				vo.setMaintainType(e.getMaintainType());
				vo.setSort(e.getSort());
				result.add(vo);
			});
		}
		return R.data(result);
	}

	/**
	 * 根据保养工单状态查询全部 模板场景分类
	 */
	@TenantIgnore
	@GetMapping("/list/all/by/plan/status")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "查询全部", notes = "传入maintainTemplateSceneType")
	public R<List<MaintainTemplateSceneTypeVO>> listAll(Integer planStatus,String keyword) {
		List<MaintainTemplateSceneTypeVO> result = new ArrayList<>();
		if(planStatus.equals(TaskStatusEnum.BY_DISABLE.getStatus())){
			List<MaintainTemplateSceneType> list;
			if(Func.isEmpty(keyword)){
				list = maintainTemplateSceneTypeService.list();
			}else {
				list = maintainTemplateSceneTypeService.list(Wrappers.<MaintainTemplateSceneType>lambdaQuery().like(MaintainTemplateSceneType::getName,keyword));
			}
			if(Func.isNotEmpty(list)){
				List<MaintainTemplateSceneTypeVO> finalResult = new ArrayList<>();
				list.forEach(e -> {
					MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
					vo.setId(e.getId());
					vo.setName(e.getName());
					vo.setDesc(e.getDesc());
					vo.setMaintainType(e.getMaintainType());
					vo.setSort(e.getSort());
					finalResult.add(vo);
				});
				result.addAll(finalResult);
				result = result.stream().sorted(Comparator.comparing(MaintainTemplateSceneTypeVO::getSort)).collect(Collectors.toList());
			}
		}else {
			List<MaintainTemplateHistory> templateHistories;
			if(Func.isEmpty(keyword)){
				templateHistories = templateHistoryService.list(Wrappers.<MaintainTemplateHistory>lambdaQuery()
					.eq(MaintainTemplateHistory::getTenantId, AuthUtil.getTenantId())
					.ge(MaintainTemplateHistory::getCreateTime, DateUtil.offsetMonth(DateUtil.date(),-12))
					.le(MaintainTemplateHistory::getCreateTime, DateUtil.date()));
			}else {
				templateHistories = templateHistoryService.list(Wrappers.<MaintainTemplateHistory>lambdaQuery()
						.like(MaintainTemplateHistory::getTemplateSceneTypeName,keyword)
					.eq(MaintainTemplateHistory::getTenantId, AuthUtil.getTenantId())
					.ge(MaintainTemplateHistory::getCreateTime, DateUtil.offsetMonth(DateUtil.date(),-12))
					.le(MaintainTemplateHistory::getCreateTime, DateUtil.date()));
			}
			if(Func.isNotEmpty(templateHistories)){
				List<MaintainTemplateSceneTypeVO> finalResult = new ArrayList<>();
				templateHistories.forEach(e -> {
					MaintainTemplateSceneTypeVO vo = new MaintainTemplateSceneTypeVO();
					vo.setId(e.getTemplateSceneTypeId());
					vo.setName(e.getTemplateSceneTypeName());
					vo.setDesc(e.getTemplateSceneTypeDesc());
					vo.setSortTime(e.getCreateTime());
					finalResult.add(vo);
				});
				result = finalResult.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e -> e.getId() + ";" + e.getName()))),ArrayList::new));
				result = result.stream().sorted(Comparator.comparing(MaintainTemplateSceneTypeVO::getSortTime).reversed()).collect(Collectors.toList());
			}
		}
		return R.data(result);
	}

	/**
	 * 自定义分页 模板场景分类
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入maintainTemplateSceneType")
	public R<IPage<MaintainTemplateSceneTypeVO>> page(MaintainTemplateSceneTypeVO maintainTemplateSceneType, Query query) {
		IPage<MaintainTemplateSceneTypeVO> pages = maintainTemplateSceneTypeService.selectMaintainTemplateSceneTypePage(Condition.getPage(query), maintainTemplateSceneType);
		return R.data(pages);
	}

	/**
	 * 新增 模板场景分类
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入maintainTemplateSceneType")
	public R save(@Valid @RequestBody MaintainTemplateSceneType maintainTemplateSceneType) {
		long count = maintainTemplateSceneTypeService.count(Wrappers.<MaintainTemplateSceneType>lambdaQuery()
			.eq(MaintainTemplateSceneType::getName,maintainTemplateSceneType.getName())
			.eq(MaintainTemplateSceneType::getMaintainType,maintainTemplateSceneType.getMaintainType()));
		if(count > 0){
			throw new ServiceException("相同业务类型下，模板场景类型名称不可重复");
		}
		return R.status(maintainTemplateSceneTypeService.save(maintainTemplateSceneType));
	}

	/**
	 * 修改 模板场景分类
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入maintainTemplateSceneType")
	public R update(@Valid @RequestBody MaintainTemplateSceneType maintainTemplateSceneType) {
		return R.status(maintainTemplateSceneTypeService.updateById(maintainTemplateSceneType));
	}

	/**
	 * 新增或修改 模板场景分类
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入maintainTemplateSceneType")
	public R submit(@Valid @RequestBody MaintainTemplateSceneType maintainTemplateSceneType) {
		return R.status(maintainTemplateSceneTypeService.saveOrUpdate(maintainTemplateSceneType));
	}


	/**
	 * 删除 模板场景分类
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		long count = templateSceneRelationService.count(Wrappers.<MaintainTemplateSceneRelation>lambdaQuery().in(MaintainTemplateSceneRelation::getSceneTypeId,Func.toLongList(ids)));
		if(count > 0){
			throw new ServiceException("当前模板场景存在已关联任务模板数据");
		}
		return R.status(maintainTemplateSceneTypeService.deleteLogic(Func.toLongList(ids)));
	}

}
